<template>
    <el-card class="box-card" :body-style="{padding: '8px', height: treeHeight + 'px'}" shadow="hover">
        <el-tree
                class="tree"
                ref="tree"
                :data="treeData"
                show-checkbox
                node-key="id"
                default-expand-all
                :default-checked-keys="defaultCheckedKeys"
                :props="defaultProps">
        </el-tree>
        <div class="buttons" style="display: flex; justify-content: center; align-items: center;">
            <el-button type="primary" size="small" icon="el-icon-edit-outline" @click="save">保 存</el-button>
            <el-button type="danger" size="small" icon="el-icon-close" @click="back">取 消</el-button>
        </div>
    </el-card>
</template>

<script>
import {mapActions, mapGetters} from 'vuex';
import { api_getUserRole, api_saveRole } from "@/api/userMgmt";

export default {
    name: 'auth-tree',
    computed: {
        ...mapGetters([ 'userAuth', 'userRole' ]),
    },
    props: {
      userId: {
        type: Number,
        require: true
      }
    },
    data() {
        return {
            treeHeight: window.innerHeight-120,
            treeData: [],
            defaultCheckedKeys: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            }
        };
    },
    methods: {
      search(){
        api_getUserRole({userId: this.userId}).then(res => {
          if (res.status == 200) {
            this.defaultCheckedKeys = res.body;
          }
        })
      },
      save() {
          let checkNodes = this.$refs.tree.getCheckedNodes().map(({id}) => (id)); //选中
          let halfCheckedNodes = this.$refs.tree.getHalfCheckedNodes().map(({id}) => (id)); //半选
          //合并集合
          let modules = Array.from(new Set(checkNodes.concat(halfCheckedNodes)));
          modules = modules.length == 0 ? '' : modules.join(",");
          if (this.userId) {
            api_saveRole({modules: modules, userId: this.userId}).then(res => {
              if (res.status == 200) {
                this.$message({ message: '保存权限成功', type: 'success' });
                this.back();
              } else {
                this.$message.error('保存权限失败');
              }
            })
          } else {
            this.$message({ message: 'info', type: 'info' });
          }

      },
      buildTree(){
         this.userAuth.forEach(item => {
             if (!item.meta.hidden) {
                 this.checkChildrenNode(item);
                 this.treeData.push(item);
             }
         });
         //构建完树形结构，加载数据
        this.search();
      },
      checkChildrenNode(item){
          item.name = item.meta.title;
          if (item.children) {
              item.children.forEach(node => {
                  this.checkChildrenNode(node);
              })
          }
      },
      back(){
        this.$emit('cancelTree');
      }
    },
    created() {
      this.$nextTick(function () {
        this.buildTree();
      })
    },
    mounted() {
        window.onresize = () => {
            return (() => {
                this.treeHeight = window.innerHeight-120;
            })();
        };
    },
}
</script>

<style>
  .tree .el-tree-node__label {
    font-size: 16px !important;
  }
  .tree .el-tree-node__content {
    height: 30px !important;
  }
</style>
